package com.yu.waterstation.app.moudles.tasklog.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.waterstation.app.moudles.address.mapper.AddressMapper;
import com.yu.waterstation.app.moudles.address.pojo.Address;
import com.yu.waterstation.app.moudles.task.mapper.TaskMapper;
import com.yu.waterstation.app.moudles.task.pojo.Task;
import com.yu.waterstation.app.moudles.tasklog.mapper.TaskLogMapper;
import com.yu.waterstation.app.moudles.tasklog.pojo.TaskLog;
import com.yu.waterstation.app.moudles.worker.mapper.WorkerMapper;
import com.yu.waterstation.app.moudles.worker.pojo.Worker;
import com.yu.waterstation.common.exception.handler.ServiceException;
import com.yu.waterstation.common.util.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@Service
public class TaskLogServiceImpl implements TaskLogService {
    @Resource
    private TaskLogMapper taskLogMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private AddressMapper addressMapper;
    @Resource
    private WorkerMapper workerMapper;


    @Override
    public Page<TaskLog> getTaskLogsOfDorm(long startTime,  String dorm, int pageNo, int pageSize) {
        QueryWrapper<TaskLog> wrapper = new QueryWrapper<TaskLog>()
                .ge("timestamp", new Date(startTime));
        if (dorm != null)
            wrapper.eq("dorm", dorm);
        wrapper.orderByDesc("timestamp");
        return taskLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Integer> rollbackTaskLog(Integer taskLogId, Integer workerId)   {
        TaskLog taskLog = taskLogMapper.selectById(taskLogId);
        if (taskLog == null)
            return Result.fail("任务记录不存在");

        if (!workerId.equals(taskLog.getWorkerId()))
            return Result.fail("撤销失败，该任务不归你负责");

        Calendar calendar = Calendar.getInstance(); // 当天时间00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        if (taskLog.getTimestamp().before(calendar.getTime())) {
            log.error("无法撤销今日之前的任务 任务记录时间{} 今日0点时刻{}", taskLog.getTimestamp(), calendar.getTime());
            return Result.fail("已经过了可以撤销的时间");
        }

        taskLogMapper.deleteById(taskLogId);

        // 回滚寝室的水桶数和水票数量 与送水时完全相反
        Address address = addressMapper.selectById(taskLog.getAddressId());
        if (address == null)
            return Result.fail("地址不存在");
        address.setBucketNum(address.getBucketNum() + taskLog.getReceiveEmptyBucketNum() - taskLog.getBucketNum());
        address.setTicketNum(address.getTicketNum() + taskLog.getBucketNum());
        addressMapper.updateById(address);

        taskMapper.deleteById(taskLog.getAddressId()); // 不管有没有 删除之前的任务
        Task task = new Task();
        task.setAddressId(taskLog.getAddressId());
        task.setTimestamp(taskLog.getTimestamp());
        // 设置叫水人
        Worker worker = workerMapper.selectById(workerId);
        if (worker != null)
            task.setPublisher("送水员-" + worker.getName());
        else
            task.setPublisher("送水员-[" + workerId + "]");

        return Result.ok(taskMapper.insert(task)); // 重新发布送水任务
    }

}

